<?php
/**
 * 
 * @author 叶风
 * Qq:    355007778
 * Email: ye.fn@163.com
 */

namespace c\shop;

class pay extends \control
{
    var $class = array('PU'=>'\c\auth\permission');
    var $table = 'shop_order';
    
    function index_home()
    {
        $this->PU->login();
        $luserID = \YF_f::$login_user_id;
        $ord = $this->db->getOne($this->table, '*', 'id='. intval($_GET['id']));
        if ($ord['state']!=1)
            $this->clue(\lang::g('Over'));
        
        $way = isset($_POST['way']) ? $_POST['way'] : $_GET['way'];
        if ($way)
            $this->pay($ord, $way);
        else
            $this->loadTemplate('shop/pay/select', array('ord'=>$ord ));
    }
    protected function pay($data, $way)
    {
        $wayD = \YF_f::initC('\c\shop\order\g')->payWay($way);
        \log::write('shop_order', 'pay', $data['id']);
        
        if ($way==1)
         {
            $this->db->save($this->table, array('pay_way'=>$wayD['name'], 'state'=>2), 'id='. $data['id']);
            $this->loadTemplate('shop/pay/w-1', array('ord'=>$data));
         }
		elseif ($way==2)
		 {
			$this->db->save($this->table, array('pay_way'=>$wayD['name']), 'id='. $data['id']);
			$a = \YF_f::initC('\c\shop\order\g')->payWay($way);
			$this->loadTemplate('shop/pay/w-bank', array('ord'=>$data, 'des'=>$a['des']));
		 }
        else{
            $this->db->save($this->table, array('pay_way'=>$wayD['name']), 'id='. $data['id']);
			
			//
		include WEB_DIR .'wapi/' . $wayD['call'];
			index_submit($data);
         }
    }
	/**
	 * 
	 * @param type $sn  订单号
	 * @param type $money  支付金额（元）
	 * @param type $trade_no   支付流水号
	 * @param type $way 支付方式
	 */
	function auto_payed($sn, $money, $trade_no, $way='')
	{
		$sn = $this->db->escape($sn);
		$r = $this->db->getOne('shop_order', '*', "sn='$sn'");
		$Msg = \YF_f::initC('\c\msg\g');
		if (!$r)
		 {
			$Msg->to(1, 'alipay no sn:'. $sn);
		 }
		elseif ($r['state']==1)
		 {
			if ($r['pay_money']!=$money)
			 {
				$Msg->to(1, 'pay money err:'. $sn);
			 }
			else{
				$r['pay_sn'] = $trade_no;
				$b = \YF_f::initC('\c\shop\order\g')->paid($r);
				if ($b)
					\log::write ('auto_payed', 'paid:'. $way . $sn);
				else
					$Msg->to(1, 'save fail:'. $sn);
			 }
		 }
	}
}
